<%@page import="java.io.*,java.sql.*,java.util.*,com.mysql.jdbc.PreparedStatement" %>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<%!
    public String[] selectCustomer(int id) {
        String[] custInfo = {"", "", "", "", "", "", "", "", "", "", "", ""};
        String sql = "SELECT CustFirstName, CustLastName, CustAddress, CustCity, CustProv, CustCountry, CustPostal, CustHomePhone, CustBusPhone, CustEmail,Password FROM customers WHERE CustomerId=" + id;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            Connection dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/TravelExperts", "root", "");
            Statement stmt = dbConn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            if (rs!=null)
                {
                    while(rs.next())
                      {
                         for (int i = 1; i <= 11; i++)
                         {
                            custInfo[i - 1] = rs.getString(i);
                         }
                        custInfo[11] = custInfo[10];
                      }
                    dbConn.close();
                } 
        } catch (ClassNotFoundException ex) {
            System.out.println("Update was NOT successful. Please contact administrtor.1-888-888-8888");
        } catch (SQLException ex) {
            System.out.println("Update was NOT successful. Please contact administrtor.1-888-888-8888");
        }
        return custInfo;
    }

    public String updateCustomer(String[] customerArray, int id) {
        String sql = "UPDATE customers SET"
                + " CustFirstName='" + customerArray[0]
                + "',CustLastName='" + customerArray[1]
                + "',CustAddress='" + customerArray[2]
                + "',CustCity='" + customerArray[3]
                + "',CustProv='" + customerArray[4]
                + "',CustCountry='" + customerArray[5]
                + "',CustCountry='" + customerArray[6]
                + "',CustHomePhone='" + customerArray[7]
                + "',CustBusPhone='" + customerArray[8]
                + "',CustEmail='" + customerArray[9]
                + "',Password='" + customerArray[10]
                + "' WHERE CustomerId=" + id;

        try {


            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException ex) {
            return "Update was NOT successful. Please contact administrtor.1-888-888-8888";
        }
            Connection dbConn;
        try {
            dbConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/TravelExperts", "root", "");

            Statement stmt;

            stmt = dbConn.createStatement();

            int rows;
        
            rows = stmt.executeUpdate(sql);
                        if (rows == 1) {
                return "Your update was a success." + " <meta http-equiv='refresh' content='1; url=itinerary.jsp'>";
            }
             dbConn.close();  // close the connection
        }
        catch (SQLException ex) {
            return "Update was NOT successful. Please contact administrtor.1-888-888-8888";
        }
        return "Update was NOT successful. Please contact administrtor.1-888-888-8888";
    }
%>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>Update</title>
        <link rel="stylesheet" type="text/css" href="main.css" />
        <script type="text/javascript">
            function trim(value) {
                return value.replace(/(^\s*)|(\s*$)/g, '');
            }

            var errMsg = {
                required: {
                    msg: 'This field is required.',
                    test: function(obj, load) {
                        return trim(obj.value).length > 0 || load || trim(obj.value) != obj.defaultValue;
                    }
                },
                email: {
                    msg: 'Not a valid email address.',
                    test: function(obj) {
                        return trim(obj.value).length <= 0 || /^[a-z0-9_+.-]+\@([a-z0-9-]+\.)+[a-z0-9]{2,4}$/i.test(obj.value);
                    }
                },
                phone: {
                    msg: 'Not a valid phone number.',
                    test: function(obj) {
                        var m = /(\d{3}).*(\d{3}).*(\d{4})/.exec(obj.value);
                        if (m)
                            obj.value = "(" + m[1] + ") " + m[2] + "-" + m[3];
                        return trim(obj.value).length <= 0 || m;
                    }
                }
            };

            function watchFields(form) {
                for (var i = 0; i < form.elements.length; i++) {
                    addEvent(form.elements[i], 'blur', function() {
                        hideErrors(this);  //add by myself
                        return validateField(this);
                    });
                }
            }
            function validateForm(form, load) {
                var valid = true;
                for (var i = 0; i < form.elements.length; i++) {
                    hideErrors(form.elements[i]);
                    if (validateField(form.elements[i], load))
                        valid = false;
                }
                return valid;
            }
            function validateField(elem, load) {
                var errors = [];
                for (var name in errMsg) {
                    var re = new RegExp('(^|\\s)' + name + '(\\s|$)');
                    if (re.test(elem.className) && !errMsg[name].test(elem, load))
                        errors.push(errMsg[name].msg);
                }
                if (errors.length)
                    showErrors(elem, errors);
                return errors.length > 0;
            }
            function hideErrors(elem) {
                var next = elem.nextSibling;
                if (next && next.nodeName == 'UL' && next.className == 'errors') {
                    elem.parentNode.removeChild(next);
                }
            }
            function showErrors(elem, errors) {
                var next = elem.nextSibling;
                if (next && (next.nodeName != 'UL' || next.className != 'errors')) {
                    next = document.createElement('ul');
                    next.className = 'errors';
                    elem.parentNode.insertBefore(next, elem.nextSibling);
                }
                for (var i = 0; i < errors.length; i++) {
                    var li = document.createElement('li');
                    li.innerHTML = errors[i];
                    next.appendChild(li);
                }
            }
            function getInputsByName(name) {
                var results = [];
                results.numChecked = 0;
                var input = document.getElementsByTagName("input");
                for (var i = 0; i < input.length; i++) {
                    if (input[i].name == name) {
                        results.push(input[i]);
                        if (input[i].checked)
                            results.numChecked++;
                    }
                }
                return results;
            }
            function addLoadEvent(func) {
                var oldonload = window.onload;
                if (typeof window.onload != 'function') {
                    window.onload = func;
                } else {
                    window.onload = function() {
                        oldonload();
                        func();
                    }
                }
            }
            function addEvent(obj, event, eventHandler) {
                if (obj.addEventListener) {
                    obj.addEventListener(event, eventHandler, false);
                } else if (obj.attachEvent) {
                    event = 'on' + event;
                    obj.attachEvent(event, eventHandler);
                }
            }
            function stopDefault(e) {
                if (e && e.preventDefault)
                    e.preventDefault();
                else
                    window.event.returnValue = false;
                return false;
            }
            function watchForm(form) {
                addEvent(form, 'submit', function(e) {
                    if (!validateForm(form))
                        stopDefault(e);
                });
            }
            addLoadEvent(function() {
                var form = document.getElementsByTagName('form')[0];
                watchFields(form);
                watchForm(form);
            });
        </script>
    </head>
    <body>
        <%
        String uid="";
        String[] customer = {"", "", "", "", "", "", "", "", "", "", "", ""};
//uid="104";
 if (!session.isNew())
        {
            uid=session.getAttribute("CustomerId").toString();
            if (uid==null)
            {
                uid="";
            }else {
                    customer = selectCustomer(Integer.parseInt(uid));
                }
        }

        if ("".equals(uid)) {
            out.println("<meta http-equiv='refresh' content='0; url=index.jsp'/>");
        } else {
                
                if (request.getParameter("Submit") != null) {

                    customer[0] = (String) request.getParameter("fname");
                    customer[1] = (String) request.getParameter("lname");
                    customer[2] = (String) request.getParameter("address");
                    customer[3] = (String) request.getParameter("city");
                    customer[4] = (String) request.getParameter("prov");
                    customer[5] = (String) request.getParameter("country");
                    customer[6] = (String) request.getParameter("postal");
                    customer[7] = (String) request.getParameter("phone");
                    customer[8] = (String) request.getParameter("busphone");
                    customer[9] = (String) request.getParameter("email");
                    customer[10] = (String) request.getParameter("pass");
                    customer[11] = (String) request.getParameter("pass2");
                    out.println("<h4 style='color:crimson'>" + updateCustomer(customer, Integer.parseInt(uid)) + "</h4>");
                    //after writing customer data empty the array so form will be empty
                    customer[0] = "";
                    customer[1] = "";
                    customer[2] = "";
                    customer[3] = "";
                    customer[4] = "";
                    customer[5] = "";
                    customer[6] = "";
                    customer[7] = "";
                    customer[8] = "";
                    customer[9] = "";
                    customer[10] = "";
                    customer[11] = "";
                }
        }
        %>
        <div id="container">
            <div id="header">Travel Experts
                <div class="nav"><a href="index.jsp">Login</a>&nbsp;&nbsp |
                    <a href="register.jsp">&nbsp;&nbsp Register</a>&nbsp;&nbsp |
                    &nbsp;&nbsp Update&nbsp;&nbsp; |
                    <a href="itinerary.jsp">&nbsp;&nbsp Itinerary</a></div>
            </div>
            <div class="login">

                <div class="uptransbox">
                    <p>Update account</p>

                    <form action="" method="post">
                        Email: <input type="text" name="email" value="<%=customer[9]%>" class="required email text" /><br />
                        Password: <input type="password" name="pass" value="<%=customer[10]%>" class="required text"/><br />
                        Re-enter Pass: <input type="password" name="pass2" value="<%=customer[11]%>" class="required text" /><br />
                        First Name:<input type="text" name="fname" value="<%=customer[0]%>" class="required text" /><br />
                        Last Name: <input type="text" name="lname" value="<%=customer[1]%>" class="required text" /><br />
                        Address: <input type="text" name="address" value="<%=customer[2]%>" class="required text" /><br />
                        City: <input type="text" name="city" value="<%=customer[3]%>" class="required text" /><br />
                        Province: <input type="text" name="prov" value="<%=customer[4]%>" class="required text" /><br />
                        Country: <input type="text" name="country" value="<%=customer[5]%>" class="required text"/>
                        Postal Code: <input type="text" name="Postal" value="<%=customer[6]%>" class="required text" /><br />
                        Phone Number: <input type="text" name="phone" value="<%=customer[7]%>" class="phone text" /><br />
                        Bus Phone: <input type="text" name="busphone" value="<%=customer[8]%>" class="phone text" />
                        <br /> 
                        <input type="submit" name="Submit" value="Submit" id="btn" class="submit"/>
                        <input type="reset" name="Reset" value="Reset" id="btn" />
                    </form>
                </div>
            </div>	
        </div>
    </body>
</html>

